package com.jay.net.clazz.socket.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPServer implements Runnable {
	public static final int MAX_DATAGRAM_BYTES = 512;
	public static final int MAX_SEND_QUEUE = 4;
	public static final int MAX_RECV_QUEUE = 40;
	DatagramSocket socket;
	DatagramPacket packet = null;

	public UDPServer(int port) throws IOException {
		this.socket = new DatagramSocket(port);
		// outgoing queue of about 4 datagrams
		socket.setSendBufferSize(MAX_DATAGRAM_BYTES * MAX_SEND_QUEUE);
		// incoming queue of about 40 datagrams, with pad byte
		socket.setReceiveBufferSize((MAX_DATAGRAM_BYTES + 1) * MAX_RECV_QUEUE);
	}

	public void run() {
		for (;;) {
			try {
				byte[] buffer = new byte[8192];
				DatagramPacket packet = new DatagramPacket(buffer,
						buffer.length);
				socket.receive(packet);
				new ConnectionHandler(socket, packet).run();
			} catch (IOException e) {
				// …
			}
		} // for (;;)
	} // run()
} // class
